﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
using Traceability.App.Instructure;

namespace Traceability.App.Api.Extensions
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddServices(this IServiceCollection services)
        {
            services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            services.AddMediatR(x => x.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly()));
            services.AddAutoMapper(typeof(MyMapper));
            return services;
        }

        public static IServiceCollection AddDbContextServices<TraceabilityDbContext>(this IServiceCollection services,string? connectionString,bool enableSqlLog)where TraceabilityDbContext : DbContext
        {
            return services.AddDbContext<TraceabilityDbContext>(builder =>
            {
                builder.UseSqlServer(connectionString, action =>
                {
                    action.EnableRetryOnFailure(
                        maxRetryCount: 10,
                        maxRetryDelay: TimeSpan.FromSeconds(60),
                        errorNumbersToAdd: null
                    );
                });
                if (enableSqlLog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure.AddFilter((categroy, level) => categroy == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).AddConsole();
                    }));
                }
            });

        }
    }
}
